﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace JinfuyuanProject.Jobs
{
    public class DatabaseBackupJob:IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            // 数据库连接字符串
            string connectionString = ConfigurationManager.AppSettings["Jinfuyuan"];

            // 备份文件保存路径
            string backupFilePath = Path.Combine("D:\\Backup", $"DatabaseBackup_{DateTime.Now:yyyyMMdd}.bak");
            string backupDir = "D:\\Backup";
            if (!Directory.Exists(backupDir))
            {
                Directory.CreateDirectory(backupDir);  // 创建目录
            }
            // 备份文件名
            if (File.Exists(backupFilePath))
            {
                File.Delete(backupFilePath);  // 删除旧的备份文件
            }
            try
            {
                // 创建 SQL 连接
                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    // 创建 SQL 命令来执行备份操作
                    var command = new SqlCommand($"BACKUP DATABASE Jinfuyuan2025 TO DISK = @backupPath", connection);
                    command.Parameters.AddWithValue("@backupPath", backupFilePath);

                    // 执行备份
                    command.ExecuteNonQuery();
                    Console.WriteLine($"数据库备份成功，备份文件路径: {backupFilePath}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库备份失败: {ex.Message}");
            }

            return Task.CompletedTask;
        }
    }
}